<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" :rules="formRules" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>单据信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
								<template #label>
									<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.BillCode" clearable class="width100" disabled placeholder="自动生成"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="备注" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100" :disabled="!canEdit"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_PersonId_FormItem"
								prop="Entity.PersonId"
								:rules="[{ required: true, message: '员工为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="员工" tooltip="关联的员工实体" />
								</template>
								<WtmPersonSelector
									v-model="stateData.vmModel.Entity.PersonId"
									@change="onPersonSelected"
									:disabled="!canEdit"
									:prefill-person="prefillPersonData"
								/>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
								<template #label>
									<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.StaffNo" clearable class="width100" disabled placeholder="选取人员后带入"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
								<template #label>
									<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100" disabled placeholder="选取人员后带入"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>加班申请信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_RecordId_FormItem" prop="Entity.RecordId">
								<template #label>
									<WtmLabelTooltip label="加班记录" tooltip="选择关联的加班记录" />
								</template>
								<el-select
									v-model="stateData.vmModel.Entity.RecordId"
									clearable
									class="width100"
									placeholder="请选择加班记录"
									@change="onScheduleRecordChange"
									:loading="scheduleRecordsLoading"
									:disabled="!canEdit"
								>
									<el-option
										v-for="record in scheduleRecords"
										:key="record.ID"
										:value="record.ID"
										:label="`${record.ShiftDate} ${record.AttendanceShiftGroupName || '未知班次'}`"
									>
										<div>
											<span>{{ record.ShiftDate }}</span>
											<span style="margin-left: 10px; color: #8492a6">{{ record.AttendanceShiftGroupName || '未知班次' }}</span>
										</div>
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_StartTime_FormItem"
								prop="Entity.StartTime"
								:rules="[{ required: true, message: '开始时间为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="开始时间" tooltip="开始时间（只能选择整点或半点）" />
								</template>
								<el-date-picker
									v-model="stateData.vmModel.Entity.StartTime"
									type="datetime"
									:disabled-date="disabledDate"
									format="YYYY-MM-DD HH:mm"
									value-format="YYYY-MM-DD HH:mm:ss"
									:disabled-hours="disabledHours"
									:disabled-minutes="disabledMinutes"
									clearable
									class="width100"
									placeholder="请选择开始时间（整点或半点）"
									:disabled="!canEdit"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_EndTime_FormItem"
								prop="Entity.EndTime"
								:rules="[{ required: true, message: '结束时间为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="结束时间" tooltip="结束时间（只能选择整点或半点）" />
								</template>
								<el-date-picker
									v-model="stateData.vmModel.Entity.EndTime"
									type="datetime"
									:disabled-date="disabledDate"
									format="YYYY-MM-DD HH:mm"
									value-format="YYYY-MM-DD HH:mm:ss"
									:disabled-hours="disabledHours"
									:disabled-minutes="disabledMinutes"
									clearable
									class="width100"
									placeholder="请选择结束时间（整点或半点）"
									:disabled="!canEdit"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_OvertimeHours_FormItem"
								prop="Entity.OvertimeHours"
								:rules="[{ required: true, message: '加班时长为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="加班时长(小时)" tooltip="加班时长" />
								</template>
								<el-input-number
									v-model="stateData.vmModel.Entity.OvertimeHours"
									:disabled="true"
									class="width100"
									placeholder="系统自动计算"
								></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_CompensationType_FormItem"
								prop="Entity.CompensationType"
								:rules="[{ required: true, message: '加班补偿方式为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="加班补偿方式" tooltip="等时调休/薪资补助" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.CompensationType" clearable class="width100" :disabled="!canEdit">
									<el-option v-for="item in COMPENSATION_TYPE_OPTIONS" :key="item.value" :value="item.value" :label="item.label"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20" v-if="stateData.vmModel.Entity.CompensationType === '等时调休'">
							<el-form-item ref="Entity_RemainingCompOffHours_FormItem" prop="Entity.RemainingCompOffHours">
								<template #label>
									<WtmLabelTooltip label="剩余调休时长" tooltip="等时调休剩余可用时长(小时)" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.RemainingCompOffHours" :disabled="true" class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Reason_FormItem" prop="Entity.Reason" :rules="[{ required: true, message: '事由为必填项', trigger: 'blur' }]">
								<template #label>
									<WtmLabelTooltip label="加班事由" tooltip="加班事由" />
								</template>
								<el-input
									v-model="stateData.vmModel.Entity.Reason"
									type="textarea"
									:rows="2"
									clearable
									class="width100"
									placeholder="请输入加班事由"
									:disabled="!canEdit"
								></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector
								v-model="stateData.vmModel.Entity.OrgId"
								label="公司"
								prop="Entity.OrgId"
								:auth="false"
								:disabled="true"
								placeholder="选取人员后带入"
							/>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmDeptSelector v-model="stateData.vmModel.Entity.GroupId" prop="Entity.GroupId" label="所属部门" :auth="false" :disabled="true" />
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, watch, type ComponentInternalInstance } from 'vue';
import { SysDailyOvertimeRequestBillApi as api } from '/@/views/daily/sysdailyovertimerequestbill/api';
import other from '/@/utils/other';
import { ISysDailyOvertimeRequestBillVm } from '/@/views/daily/sysdailyovertimerequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import { SysAttendanceRecordApi } from '/@/views/hr/sysattendancerecord/api';
import { ISearchByPersonRequest } from '/@/views/hr/sysattendancerecord/api/interface';

// 常量定义
const BILL_STATUS = {
	DRAFT: '草稿',
	FORMAL: '正文',
} as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
	IN_AUDIT: '审核中',
} as const;

const COMPENSATION_TYPE_OPTIONS = [
	{ value: '等时调休', label: '等时调休' },
	{ value: '薪资补助', label: '薪资补助' },
] as const;

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();

// 排班记录相关数据
const scheduleRecords = ref<any[]>([]);
const scheduleRecordsLoading = ref(false);
const attendanceRecordApi = SysAttendanceRecordApi();

// 动态表单验证规则
const formRules = computed(() => {
	const rules: Record<string, any[]> = {
		'Entity.CompensationType': [{ required: true, message: '请选择加班补偿方式', trigger: 'change' }],
		'Entity.StartTime': [{ required: true, message: '请选择开始时间', trigger: 'change' }],
		'Entity.EndTime': [{ required: true, message: '请选择结束时间', trigger: 'change' }],
		'Entity.OvertimeHours': [{ required: true, message: '请输入加班时长', trigger: 'blur' }],
	};

	return rules;
});

const stateData = reactive<IViewModel<ISysDailyOvertimeRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null,
			PersonId: null,
			OrgId: null,
			StaffNo: null,
			Name: null,
			RecordId: null,
			StartTime: null,
			EndTime: null,
			OvertimeHours: null,
			CompensationType: null,
			RemainingCompOffHours: null,
			Reason: null,
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
		} as any,
		ActionName: null,
		IsMyApprove: null,
	},
	AllSysGroups: [] as any[],
});

// 日期限制：前后60天
const disabledDate = computed(() => {
	return (time: Date) => {
		const today = new Date();
		const sixtyDaysAgo = new Date(today.getTime() - 60 * 24 * 60 * 60 * 1000);
		const sixtyDaysLater = new Date(today.getTime() + 60 * 24 * 60 * 60 * 1000);
		return time < sixtyDaysAgo || time > sixtyDaysLater;
	};
});

// 小时不禁用（所有小时都可选）
const disabledHours = () => {
	return [];
};

// 分钟限制：只能选择 00 和 30
const disabledMinutes = (hour: number) => {
	// 返回需要禁用的分钟数组，保留 0 和 30 可选
	const allMinutes = Array.from({ length: 60 }, (_, i) => i);
	return allMinutes.filter((minute) => minute !== 0 && minute !== 30);
};

// 计算属性
const canEdit = computed(() => {
	const billStatus = stateData.vmModel.Entity.BillStatus;
	return billStatus === BILL_STATUS.DRAFT || !billStatus;
});

const canSubmit = computed(() => canEdit.value && stateData.vmModel.Entity.ID);

// 人员选择器预填充数据
const prefillPersonData = computed(() => {
	const entity = stateData.vmModel.Entity;
	if (entity.PersonId && entity.Name) {
		return {
			ID: entity.PersonId,
			Name: entity.Name,
			StaffNo: entity.StaffNo,
		};
	}
	return null;
});

// 监听开始时间和结束时间变化，自动计算加班时长
watch(
	[() => stateData.vmModel.Entity.StartTime, () => stateData.vmModel.Entity.EndTime],
	([startTime, endTime]) => {
		if (startTime && endTime) {
			const start = new Date(startTime);
			const end = new Date(endTime);

			// 确保结束时间不早于开始时间
			if (end >= start) {
				// 计算小时数差（精确到0.5小时）
				const timeDiff = end.getTime() - start.getTime();
				const hoursDiff = timeDiff / (1000 * 3600); // 精确的小时数
				// 四舍五入到最接近的0.5小时
				const roundedHours = Math.round(hoursDiff * 2) / 2;
				stateData.vmModel.Entity.OvertimeHours = roundedHours;

				// 如果是等时调休，剩余时长等于加班时长
				if (stateData.vmModel.Entity.CompensationType === '等时调休') {
					stateData.vmModel.Entity.RemainingCompOffHours = roundedHours;
				}
			} else {
				// 如果结束时间早于开始时间，清空时长
				stateData.vmModel.Entity.OvertimeHours = null;
				stateData.vmModel.Entity.RemainingCompOffHours = null;
			}
		} else {
			// 如果任一时间为空，清空时长
			stateData.vmModel.Entity.OvertimeHours = null;
			stateData.vmModel.Entity.RemainingCompOffHours = null;
		}
	},
	{ immediate: true }
);

// 监听补偿方式变化，自动计算剩余调休时长
watch(
	() => stateData.vmModel.Entity.CompensationType,
	(compensationType) => {
		if (compensationType === '等时调休' && stateData.vmModel.Entity.OvertimeHours) {
			stateData.vmModel.Entity.RemainingCompOffHours = stateData.vmModel.Entity.OvertimeHours;
		} else {
			stateData.vmModel.Entity.RemainingCompOffHours = null;
		}
	}
);

// 统一的成功处理函数
const handleSuccess = (response: any, isSubmit = false) => {
	// 根据操作类型显示不同的消息
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
		emit('refresh');
		closeDialog();
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
		emit('refresh');
		// 保存后不关闭弹窗，更新实体数据
		if (response?.Entity) {
			stateData.vmModel.Entity = response.Entity;
		}
	}

	loading.value = false;
	nextTick(() => {
		setupHeaderButtons();
	});
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的API请求处理函数
const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	other.validateFormWithMessage(formRef.value, () => {
		loading.value = true;
		beforeSubmit();
		apiCall()
			.then((response: any) => handleSuccess(response, isSubmit))
			.catch(handleError);
	});
};

// 加载排班记录
const loadScheduleRecords = async (personId: string) => {
	if (!personId) {
		scheduleRecords.value = [];
		return;
	}

	scheduleRecordsLoading.value = true;
	try {
		// 构建查询参数 - 查询当天前30天的排班记录
		const today = new Date();
		const startDate = new Date(today.getTime() - 60 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
		const endDate = today.toISOString().split('T')[0];

		const params: ISearchByPersonRequest = {
			PersonId: personId,
			Page: 1,
			Limit: 100,
			IsPlainText: true,
			IsEmunToString: true,
			ShiftDate: [startDate, endDate],
		};

		const response = await attendanceRecordApi.getSchedulingByPerson(params);

		// 过滤出已计算的考勤记录（排除"未计算"状态）
		let filteredRecords: any[] = [];
		if (response.Data && Array.isArray(response.Data) && (response.Data as any[]).length > 0) {
			const firstData = (response.Data as any[])[0];
			if (firstData && firstData.Records && Array.isArray(firstData.Records)) {
				filteredRecords = firstData.Records.filter((record: any) => {
					return record.ID && record.ShiftDate && record.AttendanceResult && record.AttendanceResult !== '未计算';
				});
			}
		}

		scheduleRecords.value = filteredRecords;
	} catch (error) {
		console.error('加载排班记录失败:', error);
		ElMessage.error('加载排班记录失败');
		scheduleRecords.value = [];
	} finally {
		scheduleRecordsLoading.value = false;
	}
};

// 排班记录选择变化处理
const onScheduleRecordChange = (recordId: string) => {
	if (recordId) {
		const selectedRecord = scheduleRecords.value.find((record) => record.ID === recordId);
		if (selectedRecord && selectedRecord.AttendanceShift) {
			// 根据排班记录自动填充时间信息
			const shiftDate = selectedRecord.ShiftDate || new Date().toISOString().split('T')[0];
			const workStartTime = selectedRecord.AttendanceShift.WorkStartTime;
			const workEndTime = selectedRecord.AttendanceShift.WorkEndTime;

			if (workStartTime && workEndTime) {
				// 构建完整的日期时间
				stateData.vmModel.Entity.StartTime = new Date(`${shiftDate} ${workStartTime}:00`);
				stateData.vmModel.Entity.EndTime = new Date(`${shiftDate} ${workEndTime}:00`);
			}
		}
	}
};

// 人员选择变化处理
const onPersonSelected = async (value: any, person: any) => {
	if (person) {
		// 自动填充员工信息
		stateData.vmModel.Entity.StaffNo = person.StaffNo || '';
		stateData.vmModel.Entity.Name = person.Name || '';
		stateData.vmModel.Entity.OrgId = person.OrgId || '';
		stateData.vmModel.Entity.GroupId = person.GroupId || '';

		// 加载该人员的排班记录
		await loadScheduleRecords(person.ID);
	} else {
		// 清空员工信息
		stateData.vmModel.Entity.StaffNo = null;
		stateData.vmModel.Entity.Name = null;
		stateData.vmModel.Entity.OrgId = null;
		stateData.vmModel.Entity.GroupId = null;
		stateData.vmModel.Entity.RecordId = null;

		// 清空排班记录
		scheduleRecords.value = [];
	}
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {
			stateData.vmModel.Entity.BillStatus = BILL_STATUS.DRAFT;
		},
		false
	);
};

// 提交
const onSubmit = () => {
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {
			// 提交前设置状态
			stateData.vmModel.Entity.BillStatus = BILL_STATUS.FORMAL;
			stateData.vmModel.Entity.WorkflowStatus = WORKFLOW_STATUS.SUBMITTING;
		},
		true
	);
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		(stateData.vmModel.Entity as any).ID = wtmdata.ID;
	}
};

// 加载页面数据
const loadPageData = async () => {
	const API_ENDPOINTS = {
		GROUPS: '/api/SysDailyOvertimeRequestBill/GetSysGroups',
	} as const;

	const [groups, entityData] = await Promise.allSettled([
		other.getSelectList(API_ENDPOINTS.GROUPS, [], false),
		api().get(stateData.vmModel.Entity.ID ?? ''),
	]);

	// 处理成功的结果
	if (groups.status === 'fulfilled') stateData.AllSysGroups = groups.value;
	if (entityData.status === 'fulfilled') {
		other.setValue(stateData.vmModel, entityData.value);
		// 如果有人员ID，加载排班记录
		if (stateData.vmModel.Entity.PersonId) {
			await loadScheduleRecords(stateData.vmModel.Entity.PersonId);
			// 确保当前选中的排班记录在列表中
			await ensureCurrentRecordInList();
		}
	}
};

// 确保当前选中的排班记录在下拉列表中
const ensureCurrentRecordInList = async () => {
	const recordId = stateData.vmModel.Entity.RecordId;
	if (!recordId) return;

	// 检查当前记录是否已在列表中
	const existingRecord = scheduleRecords.value.find((record) => record.ID === recordId);
	if (existingRecord) return;

	// 如果不在列表中，尝试通过搜索接口获取这条记录（包含完整信息）
	try {
		const searchResponse: any = await attendanceRecordApi.search({
			PageIndex: 1,
			PageSize: 1,
			Searcher: { ID: recordId },
		});

		if (searchResponse && searchResponse.Data && searchResponse.Data.length > 0) {
			const record: any = searchResponse.Data[0];
			// 构建显示所需的字段
			const displayRecord = {
				ID: record.ID,
				ShiftDate: record.ShiftDate || '未知日期',
				AttendanceShiftGroupName: record.AttendanceShiftGroupName || record.AttendanceShift?.GroupName || record.AttendanceShift?.Name || '未知班次',
				AttendanceShift: record.AttendanceShift,
				AttendanceResult: record.AttendanceResult,
			};
			// 将记录添加到列表开头
			scheduleRecords.value.unshift(displayRecord);
		}
	} catch (error) {
		console.warn('获取选中的排班记录失败:', error);
		// 失败不影响页面显示，只是可能显示ID
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: canEdit.value,
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: canSubmit.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
